package org.example.freemarkertest;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * file:FreeMarkerTest.class
 * function:
 *
 * @author shaodan wang
 * @date 2024-10-22
 */

public class FreeMarkerTest {
    public static void main(String[] args) throws IOException, TemplateException {
        // 1. 创建并配置 FreeMarker 配置实例
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_31);
        cfg.setClassForTemplateLoading(FreeMarkerTest.class, "/templates");
        cfg.setDefaultEncoding("UTF-8");

        // 2. 定义模板数据
        Map<String, Object> templateData = new HashMap<>();

        // 模拟一个不为空的集合
        List<String> myList = Arrays.asList("apple", "banana", "cherry");
        templateData.put("myList", myList);

        // 3. 加载 FreeMarker 模板
        Template template = cfg.getTemplate("mytemplate.ftl");

        // 4. 合并模板和数据模型
        StringWriter out = new StringWriter();
        template.process(templateData, out);

        // 输出到控制台
        System.out.println(out.getBuffer().toString());
    }
}
